package org.example.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.Command.CommonMessage;
import org.example.Command.FileMessage;
import org.example.Command.RecvMessage;
import org.example.Entity.FileFactory;
import org.example.Entity.MyFile;
import org.example.Poll;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

import static org.example.Command.CommonMessage.END;
import static org.example.Constant.fileDirectory;
import static org.example.Utils.StringUtils.getNext;

public class RecvCommandServerHandler extends SimpleChannelInboundHandler<RecvMessage> implements SendFile {
    String key;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RecvMessage msg) throws Exception {
        //检查key是否存在，若存在则发送。
        if (msg.getKey() != null) this.key = msg.getKey();
        MyFile myFile = Poll.pipeline.get(key);
        check(ctx, myFile);
        Path path = Paths.get(fileDirectory + File.separator + key);
        int rootCount = path.getNameCount();
        Integer next = getNext();
        //根据key发送文件
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                //创建目录
                int dirCount = dir.getNameCount();
                if (dir.compareTo(path) != 0) {
                    Path subPath = dir.subpath(rootCount, dirCount);
                    //目录创建
                    FileMessage filePath = new FileMessage();
                    filePath.setFilePath(subPath.toFile());
                    ctx.writeAndFlush(filePath);
                }
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                //发送文件
                int fileCount = file.getNameCount();
                Path subPath = file.subpath(rootCount, fileCount);
                System.out.println("发送文件");
                SendFile.sendFile(ctx, file.toFile(), subPath.toFile(), next);
                return super.visitFile(file, attrs);
            }
        });
        //发送完毕信息
        CommonMessage commonMessage = new CommonMessage(END);
        commonMessage.setSequenceId(next);
        commonMessage.setArgs(msg.getArgs());
        ctx.writeAndFlush(commonMessage);
    }

    private void check(ChannelHandlerContext ctx, MyFile myFile) throws Exception {
        if (myFile == null) {
            ctx.writeAndFlush(new CommonMessage("密钥错误"));
            throw new Exception();
        } else if (myFile.getCounts() <= 0) {
            ctx.writeAndFlush(new CommonMessage("次数为0"));
            throw new Exception();
        } else if (FileFactory.isExpired(myFile)) {
            ctx.writeAndFlush(new CommonMessage("已过期"));
            throw new Exception();
        }
    }


}
